import { Blog } from "../model/Blog.js"
import { Op } from "sequelize"

const fn_list = async (ctx, next) => {
  let keyword = ctx.query.keyword || '';
  console.log(keyword);
  let where = {};
  if (keyword) {
    where = {
      [Op.or]: [
        { title: { [Op.like]: '%' + keyword + '%' } },
        { author: { [Op.like]: '%' + keyword + '%' } }
      ]
    };
  }
  let blogs = await Blog.findAll({ where: where });
  console.log('返回的博客数据:', blogs); // 添加调试信息
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: blogs
  };
}


const fn_getById = async (ctx, next) => {
  let id = ctx.params.id || 0;
  let blog = await Blog.findByPk(id);
  ctx.body = {
    code: 200,
    msg: '查询成功',
    data: blog
  }
}


const fn_add = async (ctx, next) => {
  ctx.body = '新增'

  let obj = ctx.request.body

  if (obj && obj.title && obj.author && obj.title.length > 0 && obj.title.length < 80 && obj.author.length > 5 && obj.author.length <= 30) {
    let blog = await Blog.create(obj);
    ctx.body = {
      code: 200,
      msg: '新增成功',
      data: blog
    }
  } else {
    ctx.body = {
      code: 300,
      msg: '标题或者作者验证不通过，请稍后重试'
    }
  }
}


const fn_put = async (ctx, next) => {
  /*
     1. 获取数据
     2. 根据业务需要处理数据
     3. 返回处理过后响应数据
  
 */
  let id = ctx.params.id || 0;
  let obj = ctx.request.body;
  await Blog.update(obj, {
    where: {
      id: id
    }
  })
  ctx.body = {
    code: 200,
    msg: '修改成功',
    data: null
  }
};


const fn_del = async (ctx, next) => {
  ctx.body = '删除'
  /*
      1. 获取前端传过来的数据
      2. 处理相关业务逻辑
      3. 返回处理过后的响应结果
  */

  // 拿到id
  let id = ctx.params.id || 0;
  console.log(id);


  // 处理业务逻辑：删除数据库中对应id的记录
  let count = await Blog.destroy({
    where: {
      id: id
    }
  })
  // 处理响应数据
  let res;
  if (count === 1) {
    res = {
      code: 200,
      msg: '删除成功',
      data: null
    }
  } else {
    res = {
      code: 400,
      msg: '删除失败',
      data: null
    }
  }

  ctx.body = res;

}


// 导出路由结构
export default [
  {
    method: 'get',
    url: '/blogs',
    fn: fn_list
  },
  {
    method: 'get',
    url: '/blogs/:id',
    fn: fn_getById
  },
  {
    method: 'post',
    url: '/blogs',
    fn: fn_add
  },
  {
    method: 'put',
    url: '/blogs/:id',
    fn: fn_put
  },
  {
    method: 'del',
    url: '/blogs/:id',
    fn: fn_del
  }
]